﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;

namespace WinDataInspector.Behavior
{
    class ListBoxJumpBehavior : Behavior<ListBox>
    {
        static ListBox control = null;

        public int JumpToLineAction
        {
            get { return (int)GetValue(JumpToLineActionProperty); }
            set { SetValue(JumpToLineActionProperty, value); }
        }

        public static readonly DependencyProperty JumpToLineActionProperty =
            DependencyProperty.Register("JumpToLineAction", typeof(int), typeof(ListBoxJumpBehavior), new FrameworkPropertyMetadata(OnJumpToLineActionPropertyChanged));

        private static void OnJumpToLineActionPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
        {
            if ((int)e.NewValue >= 0)
            {                
                control.SelectedIndex = (int)e.NewValue;                
                control.Items.MoveCurrentTo(control.SelectedItem);
                control.ScrollIntoView(control.SelectedItem);
                control.UpdateLayout();
            }
        }

        protected override void OnAttached()
        {
            base.OnAttached();

            control = this.AssociatedObject;
            SetCurrentValue(JumpToLineActionProperty, (int)control.SelectedIndex);
        }
    }
}
